var rootPath = '';//kk.getRootPath();

/* postDom */
var postDom = '\
<div class="box box-skin-inner sub-content">\
	<div class="box-header with-border">\
		<span class="box-title"></span>\
		<div class="box-tools pull-right">\
			<button type="button" class="btn btn-flat btn-box-tool btnCancel" data-widget="remove"><i class="fa fa-times"></i></button>\
		</div>\
	</div>\
	<div class="box-body">\
	<form class="form-horizontal" id="postForm">\
		<div class="nav-tabs-custom no-margin">\
			<ul class="nav nav-tabs">\
			    <li class="active"><a href="#c1" data-toggle="tab" aria-expanded="true">基本信息</a></li>\
    			<li class=""><a href="#c2" data-toggle="tab" aria-expanded="false">SEO设置</a></li>\
			    <li class=""><a href="#c3" data-toggle="tab" aria-expanded="false">详细内容</a></li>\
			</ul>\
			<div class="tab-content">\
				<div class="tab-pane active" id="c1">\
					<div class="row">\
						<div class="col-sm-7">\
							<div class="form-group">\
								<label for="myFile" class="col-sm-2 control-label">图片</label>\
								<div class="col-sm-10">\
									<input type="file" id="myFile" name="file" />\
									<input type="hidden" id="thumb" name="thumb" />\
								</div>\
							</div>\
							<div class="form-group">\
								<label for="cname" class="col-sm-2 control-label">栏目</label>\
								<div class="col-sm-10">\
									<input type="hidden" id="cid" name="cid" />\
									<div class="input-group">\
									    <input type="text" class="form-control" id="cname" name="cname" />\
										<span class="input-group-btn">\
											<button type="button" class="btn btn-info btn-flat" onclick="showMenu();">选择</button>\
										</span>\
									</div>\
									<div id="menuContent" class="menuContent" style="display:none; position:absolute; background-color: #f4f4f4; z-index: 4002;">\
										<ul id="parentTree" class="ztree"></ul>\
									</div>\
								</div>\
							</div>\
							<div class="form-group">\
								<label for="title" class="col-sm-2 control-label">文章标题<span class="text-red">*</span></label>\
								<div class="col-sm-10">\
									<input type="text" class="form-control" id="title" name="title" placeholder="文章标题" />\
								</div>\
							</div>\
							<div class="form-group">\
								<label for="author" class="col-sm-2 control-label">作者<span class="text-red">*</span></label>\
								<div class="col-sm-10">\
									<input type="text" class="form-control" id="author" name="author" placeholder="作者" />\
								</div>\
							</div>\
							<div class="form-group">\
								<label for="viewCount" class="col-sm-2 control-label">浏览次数</label>\
								<div class="col-sm-10">\
									<input type="number" class="form-control" id="viewCount" name="view_count" placeholder="浏览次数" value="0" min="0" />\
								</div>\
							</div>\
							<div class="form-group">\
								<label for="sortOrder" class="col-sm-2 control-label">排序</label>\
								<div class="col-sm-10">\
									<input type="number" class="form-control" id="sortOrder" name="sort_order" placeholder="排序" value="0" min="0" />\
								</div>\
							</div>\
							<div class="form-group rm-or-hide">\
								<label for="updateTime" class="col-sm-2 control-label">更新时间</label>\
								<div class="col-sm-10">\
									<input type="text" class="form-control" id="updateTime" name="updateTime" placeholder="更新时间" />\
								</div>\
							</div>\
							<div class="form-group rm-or-hide">\
								<label for="addTime" class="col-sm-2 control-label addTime">添加时间</label>\
								<div class="col-sm-10">\
									<input type="text" class="form-control" id="addTime" name="addTime" placeholder="添加时间" />\
								</div>\
							</div>\
						</div>\
						<div class="col-sm-5">\
							<div class="foo">\
								<p class="text-muted">1. 图片的尺寸为800*450</p>\
								<p class="text-muted">2. 标题根据页面是否显示而确定是否需要填入</p>\
								<p class="text-muted">3. 背景颜色主要用于轮播图片</p>\
								<p class="text-muted">4. 排序越小，实际显示越靠前</p>\
								<p class="text-muted">5. 链接地址可填入本系统的网站或课程链接地址（格式为wx/<path>.do）或其它任意可访问网址</p>\
								<p class="text-muted">6. 图片说明根据页面是否显示而确定是否需要填入</p>\
							</div>\
						</div>\
					</div>\
				</div>\
				<div class="tab-pane" id="c2">\
					<div class="row">\
						<div class="col-sm-7">\
							<div class="form-group">\
								<label for="seo_title" class="col-sm-2 control-label">SEO标题</label>\
								<div class="col-sm-10">\
									<input type="text" class="form-control" id="seo_title" name="seo_title" placeholder="SEO标题" />\
								</div>\
							</div>\
							<div class="form-group">\
								<label for="seo_keywords" class="col-sm-2 control-label">SEO关键字</label>\
								<div class="col-sm-10">\
									<input type="text" class="form-control" id="seo_keywords" name="seo_keywords" placeholder="SEO关键字" />\
								</div>\
							</div>\
							<div class="form-group">\
								<label for="seo_description" class="col-sm-2 control-label">SEO描述</label>\
								<div class="col-sm-10">\
									<input type="text" class="form-control" id="seo_description" name="seo_description" placeholder="SEO描述" />\
								</div>\
							</div>\
						</div>\
						<div class="col-sm-5">\
							<div class="foo">\
								<p class="text-muted">1. 图片的尺寸为800*450</p>\
								<p class="text-muted">2. 标题根据页面是否显示而确定是否需要填入</p>\
								<p class="text-muted">3. 背景颜色主要用于轮播图片</p>\
								<p class="text-muted">4. 排序越小，实际显示越靠前</p>\
								<p class="text-muted">5. 链接地址可填入本系统的网站或课程链接地址（格式为wx/<path>.do）或其它任意可访问网址</p>\
								<p class="text-muted">6. 图片说明根据页面是否显示而确定是否需要填入</p>\
							</div>\
						</div>\
					</div>\
				</div>\
				<div class="tab-pane" id="c3">\
					<div class="row">\
						<div class="col-sm-7">\
							<div class="form-group">\
								<label for="summary" class="col-sm-2 control-label">摘要</label>\
								<div class="col-sm-10">\
									<textarea class="form-control" rows="6" id="summary" name="summary" placeholder="摘要"></textarea>\
								</div>\
							</div>\
							<div class="form-group">\
								<label for="content" class="col-sm-2 control-label">详细介绍</label>\
								<div class="col-sm-10">\
									<script type="text/plain" id="myEditor" name="content"></script>\
								</div>\
							</div>\
						</div>\
						<div class="col-sm-5">\
							<div class="foo">\
								<p class="text-muted">1. 图片的尺寸为800*450</p>\
								<p class="text-muted">2. 标题根据页面是否显示而确定是否需要填入</p>\
								<p class="text-muted">3. 背景颜色主要用于轮播图片</p>\
								<p class="text-muted">4. 排序越小，实际显示越靠前</p>\
								<p class="text-muted">5. 链接地址可填入本系统的网站或课程链接地址（格式为wx/<path>.do）或其它任意可访问网址</p>\
								<p class="text-muted">6. 图片说明根据页面是否显示而确定是否需要填入</p>\
							</div>\
						</div>\
					</div>\
				</div>\
			</div>\
		</div>\
		<div>\
			<input type="hidden" name="id" />\
		</div>\
	</form>\
	</div>\
	<div class="box-footer text-center">\
	    <button type="button" class="btn btn-info btn-flat btnOK">确定</button>\
	    <button type="button" class="btn btn-default btn-flat btnCancel">取消</button>\
	</div>\
</div>\
';

/* CRUD 1: Create, 2: Read, 3: Update, 4: Delete */
var CREATE = 1, READ = 2, UPDATE = 3, DELETE = 4;
function CRUDPostFunc(operCode, id, index) {
	var canOpen = false;
	var url;
	var obj;
	
	if (operCode == CREATE) {
		canOpen = true;
	} else if (operCode == READ || operCode == UPDATE) {
		url = rootPath + '/Content/Post/find?id=' + id;
		obj = kk.getObj(url);
		if (obj != null) {
			canOpen = true;
		}
	} else if (operCode == DELETE) {
		url = rootPath + '/Content/Post/delete?id=' + id;
		kk.deleteObj(url, '#table');
	} else {
		return false;
	}
	
	if (!canOpen) {
		return false;
	}
		
	$('.main-content').hide();
	$('.main-content').after(postDom);
	
	var xqu = xqupload('#myFile', {
		uploadUrl			: rootPath + '/Asset/Upload/upload?savePath=post_thumb',
        recvObj				: '#thumb'
    });
	UE.delEditor('myEditor');
	var myEditor = UE.getEditor('myEditor');
	
	if (operCode == CREATE) {
		$('.box-title').empty().append('添加');

		initTree();
    	xupload('#myFile', {
    		height: 220,
    		changeHandler: function($this) {
    			$('#thumb').val('');
    			
    			lrz($('#myFile')[0].files[0], {width: 800, quality: 0.8}).then(function (rst) {
    	            // 处理成功会执行
    	            console.log(rst);
    	            $this.setFile(rst.base64);
        			
        			var filename = $('#myFile').val();
        		    var fileExt = (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename.toLowerCase()) : '';			// fileExt
        		    var key = kk.getProjectName() + '/posts/' + new Date().format("yyMMddhhmmssS") + kk.mathRand(1) + '.' + fileExt;
        			xqu.upload(rst.formData, key);
    	        }).catch(function (err) {
    	            // 处理失败会执行
    	        }).always(function () {
    	            // 不管是成功失败，都会执行
    	        });
    		}
    	});

		$('.rm-or-hide').remove();
	} else if (operCode == READ) {
		$('.box-title').empty().append('查看');
		$('.btnOK').hide();
		$('.btnCancel').text('关闭');

		$('#postForm').setForm(obj);
		initTree(obj.id, obj.cid);
    	xupload('#myFile', {
    		height: 220,
    		defaultFile: rootPath + '/' + obj.thumb,
    		isDisabled: true
    	});
		myEditor.ready(function() {											// 需要ready后执行，否则可能报错
			myEditor.setDisabled('fullscreen');
			myEditor.setContent(obj.content);
        });
		$('#addTime').val(obj.add_time);
		$('#updateTime').val(obj.update_time);

		$('#postForm').find(':input').attr("disabled", "disabled");			// 习惯性地处理
	} else if (operCode == UPDATE) {
		$('.box-title').empty().append('编辑');
		
		$('#postForm').setForm(obj);
		initTree(obj.id, obj.cid);
    	xupload('#myFile', {
    		height: 220,
    		defaultFile: rootPath + '/' + obj.thumb,
    		changeHandler: function($this) {
    			$('#thumb').val('');
    			
    			lrz($('#myFile')[0].files[0], {width: 800, quality: 0.8}).then(function (rst) {
    	            // 处理成功会执行
    	            console.log(rst);
    	            $this.setFile(rst.base64);
        			
        			var filename = $('#myFile').val();
        		    var fileExt = (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename.toLowerCase()) : '';			// fileExt
        		    var key = kk.getProjectName() + '/posts/' + new Date().format("yyMMddhhmmssS") + kk.mathRand(1) + '.' + fileExt;
        			xqu.upload(rst.formData, key);
    	        }).catch(function (err) {
    	            // 处理失败会执行
    	        }).always(function () {
    	            // 不管是成功失败，都会执行
    	        });
    		}
    	});
		myEditor.ready(function() {											// 需要ready后执行，否则可能报错
			myEditor.setContent(obj.content);
        });

		$('.rm-or-hide').hide();
	}
	
	var validator = $("#postForm").validate({
		onfocusout: function(element) {
			$(element).valid();
		},
        rules: {
        	title: "required",
        	author: "required",
        },
        messages: {
        	title: "请输入标题",
        	author: "请输入作者",
        }
    });
	
	$('.btnOK').off('click').on('click', function() {
 		if (validator.form() && doCU(operCode, id, index)) {
			$('.sub-content').remove();
			$('.main-content').show();
 		}
	});
	
	$('.btnCancel').off('click').on('click', function() {
		xqu.abort();
		
		$('.sub-content').remove();
		$('.main-content').show();
	});
}

/* Create & Update */
function doCU(operCode, id, index) {
//	$('#authorName').val($("#authorId").find("option:selected").text());		// 提交表单前为authorName赋值
	
    var url;
    var method;
	var jsonStr = JSON.stringify($('#postForm').serializeObject());
	var result;
	
	if (operCode == CREATE) {		
	 	url = rootPath + '/Content/Post/save';
		method = "POST";
		result = kk.doStrAjax(url, method, jsonStr);
		
	    if (result.code == 0) {
	    	$('#table').bootstrapTable('insertRow', {
				index: 0,
				row: result.obj
			});

	    	return true;
		}
	} else if (operCode == UPDATE) {
	 	url = rootPath + '/Content/Post/update?id=' + id;
		method = "PUT";
		result = kk.doStrAjax(url, method, jsonStr);
		
	    if (result.code == 0) {
	    	$('#table').bootstrapTable('updateRow', {
	    		index: index,
	    		row: result.obj
	    	});

	    	return true;
		}
	}
	
	return false;
}

/* init tree */
function initTree(id, pid) {
	pid = pid === undefined ? 1 : pid;					// pid <==> 1
	
	var setting = {
		async: {
			enable: true,
			type: "get",
			url: rootPath + '/Content/Category/getAll',
			autoParam: ["id", "name"],
			dataFilter: ajaxDataFilter
		},
		callback: {
			onClick: onClick,
			onAsyncSuccess: zTreeOnAsyncSuccess
		}, 
		data: {
			simpleData: {
				enable: true,
				idKey: "id",
				pIdKey: "pid",
				rootPId: 0
			},
			key: {
	            url: "xUrl"
	        }
		}
	};
	
	function ajaxDataFilter(treeId, parentNode, responseData) {
	    return responseData.obj;
	}
	
	function onClick(e, treeId, treeNode) {
//		if (treeNode.isParent) {										// 当是父节点 返回false 不让选取
//			return false;
//		}
		$('#cid').val(treeNode.id);
		$('#cname').val(treeNode.name);
	}
	
	function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {		// 加载成功后赋值
		var node = zTreeObj.getNodeByParam("id", pid);
		$('#cid').val(pid);
		$('#cname').val(node.name);
	}

	zTreeObj = $.fn.zTree.init($("#parentTree"), setting);
}


/* audit */
function auditFunc(id, index) {
	var url = rootPath + '/Content/Post/audit?id=' + id + '&status=';
	
	xpopup.confirm({
    	title: '审核',
        msg: '审核通过？',
        buttons: [{
            text: '通过',
            'class': 'btn btn-success',
            handler: function ($this) {
                var xloading = xpopup.loading();
                
    			$.ajax({
    				type: 'PUT',
    				url : url + '1',
    				dataType: 'json',
    				async : false,
    				success: function(data) {
    		        	xloading.destroy();

    					if (data.code == 0) {
    				   		xpopup.notify({
    				           	style: 'mini',
    				           	type: 'success',
//    				           	title: '操作成功',
    		   	                msg: data.msg,
    							delay: 1000,
    							position: 'center',
    						});

    	                	$('#table').bootstrapTable('updateRow', {
    	        	    		index: index,
    	        				row: data.obj
    	        	    	});
    					} else {
            				kk.extOnLoadSuccess(data);
    					}
    				},
    				error: kk.extError
    			});
    			
        		$this.destroy();
            }
        }, {
            text: '不通过',
            'class': 'btn btn-danger',
            handler: function ($this) {
                var xloading = xpopup.loading();
                
    			$.ajax({
    				type: 'PUT',
    				url : url + '2',
    				dataType: 'json',
    				async : false,
    				success: function(data) {
    		        	xloading.destroy();

    					if (data.code == 0) {
    				   		xpopup.notify({
    				           	style: 'mini',
    				           	type: 'success',
//    				           	title: '操作成功',
    		   	                msg: data.msg,
    							delay: 1000,
    							position: 'center',
    						});

    	                	$('#table').bootstrapTable('updateRow', {
    	        	    		index: index,
    	        				row: data.obj
    	        	    	});
    					} else {
            				kk.extOnLoadSuccess(data);
    					}
    				},
    				error: kk.extError
    			});
    			
        		$this.destroy();
            }
        }, {
            text: '取消',
            'class': 'btn btn-default',
            handler: function ($this) {
        		$this.destroy();
            }
        }]
    });
}

/* batRefreashPostFunc */
function batRefreashPostFunc() {
	var xloading = xpopup.loading();
	
   	$.ajax({
   		type: 'PUT',
   		url: rootPath + '/Content/Post/batRefreash',
   		data: null,
        dataType: 'json',
       	success: function(data) {
       		xloading.destroy();
       		
       		if (data.code == 0) {
       			$('#table').bootstrapTable('refresh');

		   		xpopup.notify({
		           	style: 'mini',
		           	type: 'success',
//		           	title: '操作成功',
   	                msg: data.msg,
					delay: 1000,
					position: 'center',
				});
   			}
       	}
   	});
}

/* batAuditPostFunc */
function batAuditPostFunc() {
	var xloading = xpopup.loading();
	
   	$.ajax({
   		type: 'PUT',
   		url: rootPath + '/Content/Post/batAudit',
   		data: null,
        dataType: 'json',
       	success: function(data) {
       		xloading.destroy();
       		
       		if (data.code == 0) {
       			$('#table').bootstrapTable('refresh');

		   		xpopup.notify({
		           	style: 'mini',
		           	type: 'success',
//		           	title: '操作成功',
   	                msg: data.msg,
					delay: 1000,
					position: 'center',
				});
   			}
       	}
   	});
}